package com.his.system.manager.exception;

import com.alibaba.fastjson.JSONObject;
import com.his.system.manager.base.BaseResult;
import com.his.system.manager.base.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 全局异常处理类
 *
 * @Description
 * @Author Admin
 * @Date 2020-06-14 17:55:34
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    private static int msgLength = 80;
    @Value("${spring.application.name:appName}")
    private String srvName;
    @Value("${ncdcloud.system.manager.RuntimeExceptionMsg:系统繁忙,请稍后再试!}")
    private String runtimeExceptionMsg;

    /**
     * 运行异常
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler({RuntimeException.class})
    public BaseResult handleRuntimeException(RuntimeException e) {
        e.printStackTrace();
        log.error("服务" + srvName + "运行异常:", e);

        String msg = e.getMessage();
        if (!StringUtils.isBlank(msg)) {
            msg = ResponseCode.ERROR.getMessage();
        }
        return BaseResult.build(false, handleMsg(msg), ResponseCode.ERROR.getCode(), new JSONObject());
    }

    /**
     * 业务异常
     *
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler({BuzException.class})
    public BaseResult handleBuzException(BuzException e) {
        log.info("服务" + srvName + "业务异常:", e);
        Integer code = e.getCode();
        if (code == null) {
            code = ResponseCode.ERROR.getCode();
        }
        return BaseResult.build(false, handleMsg(e.getMessage()), code, new JSONObject());
    }

    /**
     * 校验错误处理
     *
     * @param e 错误信息集合
     * @return 错误信息
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public BaseResult validationBodyException(MethodArgumentNotValidException e) {
        BindingResult result = e.getBindingResult();
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();
            for (ObjectError p : errors) {
                FieldError fieldError = (FieldError) p;
                String message = fieldError.getDefaultMessage();
                log.info("服务{}数据校验错误 : object={},field={},errorMessage={}", srvName, fieldError.getObjectName(), fieldError.getField(), message);
                return BaseResult.buildFailure(handleMsg(message), new JSONObject());
            }
        }
        return BaseResult.buildFailure(handleMsg(e.getMessage()));
    }

    public static String handleMsg(String message) {
        return (message != null && message.length() > msgLength) ? message.substring(0, msgLength) : message;
    }
}